package de.wittekind.bundesjugendspiele.server.mysqlTools;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class OpenShiftMySQLConnectionManager extends MySQLConnectionManager {

	{
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();
		} catch (InstantiationException | IllegalAccessException
				| ClassNotFoundException ex) {
			ex.printStackTrace();
		}
	}

	public static void initIfRequired() {
		try {
			if (getConnection() == null || getConnection().isClosed())
				init();
		} catch (SQLException ex) {
			ex.printStackTrace();
		}
	}

	public static void init() throws SQLException {

		close();

		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx
					.lookup("java:jboss/datasources/MysqlDS");
			connection = ds.getConnection();
		} catch (NamingException ex) {
			ex.printStackTrace();
		}
	}

	public static void initLocal(String url) throws SQLException {
		close();
		connection = DriverManager.getConnection(url);
	}

	public static void reset() {
		try {
			Connection c = getConnection();
			Statement stmt = c.createStatement();
			MySQLSetup.addQueries(stmt, OpenShiftMySQLConnectionManager.class
					.getResourceAsStream("tables.sql"));
			clearTables();
			MySQLSetup.addQueries(stmt, OpenShiftMySQLConnectionManager.class
					.getResourceAsStream("samples.sql"));
			stmt.executeBatch();
		} catch (SQLException ex) {
			ex.printStackTrace();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
